package org.tis.tools.abf.module.sys.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.tis.tools.abf.module.ac.entity.AcApp;
import org.tis.tools.abf.module.ac.service.IAcAppService;
import org.tis.tools.abf.module.sys.controller.request.SysDictDelRequest;
import org.tis.tools.abf.module.sys.dao.SysRunConfigMapper;
import org.tis.tools.abf.module.sys.entity.SysDictItem;
import org.tis.tools.abf.module.sys.entity.SysRunConfig;
import org.tis.tools.abf.module.sys.entity.vo.SysRunConfigDetail;
import org.tis.tools.abf.module.sys.exception.SYSExceptionCodes;
import org.tis.tools.abf.module.sys.exception.SysManagementException;
import org.tis.tools.abf.module.sys.service.ISysDictItemService;
import org.tis.tools.abf.module.sys.service.ISysRunConfigService;
import org.tis.tools.core.utils.StringUtil;
import org.tis.tools.model.exception.i18.ExceptionCodes;

import java.util.ArrayList;
import java.util.List;

import static org.tis.tools.core.utils.BasicUtil.wrap;

/**
 * <pre>
 * 系统参数（SYS_RUN_CONFIG）管理服务功能的实现类
 *
 * <pre>
 *
 * @author megapro
 *
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class SysRunConfigServiceImpl extends ServiceImpl<SysRunConfigMapper, SysRunConfig> implements ISysRunConfigService {

    /** 拷贝新增时，代码前缀  */
    private static final String CODE_HEAD_COPYFROM = "Copyfrom-";
    @Autowired
    private ISysRunConfigService sysRunConfigService;
    @Autowired
    private IAcAppService acAppService;
    @Autowired
    private ISysDictItemService sysDictItemService;

    /**
     * 查询所有系统运行参数
     */
    @Override
    public Page<SysRunConfigDetail> queryAllSysRunConfig(Page<SysRunConfig> page, Wrapper<SysRunConfig> wrapper) throws
            SysManagementException {

        Page<SysRunConfigDetail> configDetailPage = new Page<SysRunConfigDetail>();
        List<SysRunConfigDetail> configDetailList = new ArrayList<SysRunConfigDetail>();

        Page<SysRunConfig> configPage = new Page<SysRunConfig>();
        configPage = selectPage(page,wrapper);
        List<SysRunConfig> configList = configPage.getRecords();

        if (null != configList){
            for (SysRunConfig sysRunConfig : configList){
                if (null != sysRunConfig){
                    if (!StringUtil.isEmpty(sysRunConfig.getGuidApp())){
                        //查询应用的name
                        AcApp acApp = acAppService.selectById(sysRunConfig.getGuidApp());
                        String appName = "";
                        if (null != acApp){
                            appName = acApp.getAppName();
                        }

                        //查询业务字典guid和字典项名称
                        Wrapper<SysDictItem> itemWrapper = new EntityWrapper<SysDictItem>();
                        itemWrapper.eq(SysDictItem.COLUMN_ITEM_VALUE,sysRunConfig.getValue());

                        SysDictItem sysDictItem = sysDictItemService.selectOne(itemWrapper);

                        String dictItemName = "";
                        String dictGuid = "";

                        if (null != sysDictItem){
                            dictItemName = sysDictItem.getItemName();
                            dictGuid = sysDictItem.getGuidDict();
                        }else {
                            dictItemName = sysRunConfig.getValue();
                        }

                        SysRunConfigDetail sysRunConfigDetail = new SysRunConfigDetail(sysRunConfig,appName,
                                dictItemName,dictGuid);
                        configDetailList.add(sysRunConfigDetail);
                    }else {
                        //查询业务字典guid和字典项名称
                        Wrapper<SysDictItem> itemWrapper = new EntityWrapper<SysDictItem>();
                        itemWrapper.eq(SysDictItem.COLUMN_ITEM_VALUE,sysRunConfig.getValue());

                        SysDictItem sysDictItem = sysDictItemService.selectOne(itemWrapper);

                        String dictItemName = "";
                        String dictGuid = "";

                        if (null != sysDictItem){
                            dictItemName = sysDictItem.getItemName();
                            dictGuid = sysDictItem.getGuidDict();
                        }else {
                            dictItemName = sysRunConfig.getValue();
                        }

                        SysRunConfigDetail sysRunConfigDetail = new SysRunConfigDetail(sysRunConfig,"",dictItemName,dictGuid);
                        configDetailList.add(sysRunConfigDetail);
                    }
                }
            }
        }

        configDetailPage.setCondition(configPage.getCondition());
        configDetailPage.setRecords(configDetailList);
        configDetailPage.setTotal(configPage.getTotal());
        configDetailPage.setSize(configPage.getSize());
        configDetailPage.setCurrent(configPage.getCurrent());

        return configDetailPage;
    }

    @Override
    public SysRunConfig createSysRunConfig(String guidApp, String groupName, String keyName, String valueFrom, String value, String description) throws SysManagementException {

        SysRunConfig sysRunConfig = new SysRunConfig();
        sysRunConfig.setGuidApp(guidApp);
        sysRunConfig.setGroupName(groupName);
        sysRunConfig.setKeyName(keyName);
        sysRunConfig.setValueFrom(valueFrom);
        sysRunConfig.setValue(value);
        sysRunConfig.setDescription(description);
        insert(sysRunConfig);
        return sysRunConfig;
    }

    @Override
    public SysRunConfig editSysRunConfig(String guid,String guidApp, String groupName, String keyName, String valueFrom, String value, String description) throws SysManagementException {

        EntityWrapper<SysRunConfig> wrapper = new EntityWrapper<>();
        wrapper.eq(SysRunConfig.COLUMN_GUID,guid);
        if (guid == null  || guid == ""){
            throw new SysManagementException(ExceptionCodes.NOT_ALLOW_NULL_WHEN_DELETE,wrap("GUID","SYS_RUN_CONFIG"));
        }
        if(selectOne(wrapper) == null){
            throw new SysManagementException(
                    ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                    wrap(SysRunConfig.COLUMN_GUID,guid),SysRunConfig.COLUMN_GUID);
        }
        SysRunConfig sysRunConfig = new SysRunConfig();
        sysRunConfig.setGuidApp(guidApp);
        sysRunConfig.setGroupName(groupName);
        sysRunConfig.setKeyName(keyName);
        sysRunConfig.setValueFrom(valueFrom);
        sysRunConfig.setValue(value);
        sysRunConfig.setDescription(description);
        update(sysRunConfig,wrapper);
        return sysRunConfig;
    }

    /**
     * <p>删除系统运行参数</p>
     */
    @Override
    public SysRunConfig deleteSysRunConfig(String guid) throws SysManagementException {

        if (guid == null || guid == ""){
            throw new SysManagementException(ExceptionCodes.NOT_ALLOW_NULL_WHEN_DELETE,wrap("GUID","SYS_RUN_CONFIG"));
        }
        EntityWrapper<SysRunConfig> wrapper = new EntityWrapper<>();
        wrapper.eq(SysRunConfig.COLUMN_GUID,guid);
        SysRunConfig sysRunConfig = selectOne(wrapper);
        if(sysRunConfig == null){
            throw new SysManagementException(
                    ExceptionCodes.NOT_FOUND_WHEN_QUERY,
                    wrap(SysRunConfig.COLUMN_GUID,guid),SysRunConfig.COLUMN_GUID);
        }
        delete(wrapper);
        return sysRunConfig;
    }
    /**
     * <p>查询一条系统运行参数</p>
     */
    @Override
    public SysRunConfig queryOneSysRunConfig(String guid) throws SysManagementException {

        EntityWrapper<SysRunConfig> wrapper = new EntityWrapper<>();
        wrapper.eq(SysRunConfig.COLUMN_GUID,guid);
        return selectOne(wrapper);
    }

    /**
     * 批量删除
     */
    @Override
    public List<SysRunConfig> deleteSysConfigList(SysDictDelRequest sysDictDelRequest) throws SysManagementException {

        List<SysRunConfig> delList = new ArrayList<SysRunConfig>();

        List<String> sysRunConfigList = sysDictDelRequest.getDeleteList();
        //判断列表中的guid所对应的业务字典都存在,并且没有系统级的业务字典
        if (null != sysRunConfigList || 0 != sysRunConfigList.size()){
            for (String sysRunConfigGuid : sysRunConfigList){
                if (!StringUtil.isEmpty(sysRunConfigGuid)){
                    SysRunConfig sysRunConfig =selectById(sysRunConfigGuid);
                    if (null == sysRunConfig){
                        throw new SysManagementException(SYSExceptionCodes.NOT_FOUND_SYS_RUN_CONFIG,wrap
                                ("找不到对应记录或已经被删除"));
                    }
                    delList.add(sysRunConfig);
                }
            }
        }else {
            throw new SysManagementException(SYSExceptionCodes.LAKE_PARMS_FOR_DELETE_SYS_DICT_LIST,wrap("批量删除时参数为空!"));
        }

        for (SysRunConfig sysRunConfig : delList){
            if (null != delList){
                deleteById(sysRunConfig.getGuid());
            }
        }
        return delList;
    }
}

